/**
 * 
 */
package com.ninjascript.tanooki;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Scott
 *
 */
public class CsvMarshaller extends Marshaller {

	private BufferedReader reader;
	private String colSeparator = ",";

	public CsvMarshaller(File file) throws Exception {
		reader = new BufferedReader(new FileReader(file));
	}

	@Override
	protected ArrayList<String> parseColNames() throws Exception {		
		ArrayList<String> colNames = new ArrayList<String>();
		String line = reader.readLine();
		colNames.addAll(Arrays.asList(line.split(colSeparator)));		
		return colNames;		
	}

	@Override
	protected ArrayList<Map<String, Object>> parseRows(ArrayList<String> colNames) throws Exception {

		ArrayList<Map<String, Object>> rowList = new ArrayList<Map<String, Object>>();
		HashMap<String, Object> row;
		String line;
		String[] splitLine;

		while ((line = reader.readLine()) != null) {	

			row = new HashMap<String, Object>();
			splitLine = line.split(colSeparator);

			for (int i = 0; i < splitLine.length; i++) {
				
				if (splitLine[i].isEmpty() || "null".equals(splitLine[i])) {
					row.put(colNames.get(i), null);
				}
				else if ("true".equals(splitLine[i]) || "false".equals(splitLine[i])) {
					row.put(colNames.get(i), new Boolean(splitLine[i]));
				}
				else if (splitLine[i].matches("^[-]*[0-9]+$")) {
					row.put(colNames.get(i), new Integer(splitLine[i]));
				}
				else if (splitLine[i].matches("^[-]*[0-9]+[.][0-9]+$")) {
					row.put(colNames.get(i), new Double(splitLine[i]));
				}
				else {
					row.put(colNames.get(i), splitLine[i]);
				}

			}

			rowList.add(row);
		}	

		return rowList;

	}

	public String getColSeparator() {
		return colSeparator;
	}

	public void setColSeparator(String colSeparator) {
		this.colSeparator = colSeparator;
	}

}
